from google.appengine.api import users
import urllib
import base64
import datetime

import logging

from google.appengine.api import urlfetch
from django.http import HttpResponse, HttpResponseRedirect
from google.appengine.api import users

from mysecs.models import time_details

def login_required(func):
    def _wrapper(request, *args, **kw):
        user = users.get_current_user()
        if user:
            return func(request, *args, **kw)
        else:
            return HttpResponseRedirect(users.create_login_url(request.get_full_path()))
    return _wrapper

def strToDateTime(dt_in_string):
    """convert string into date time"""
    date,time = dt_in_string.split(' ')
    yr,mon,dt=date.split('-')
    hr,min,sec=time.split(':')
    return (int(yr),int(mon),int(dt),int(hr),int(min),int(sec))
    
#@login_required
def update(request):
    resp = HttpResponse()    
    logging.info("###########")
    logging.info("Updating with request method: %s path is:%s" % (request.method, request.path))
    logging.info("request params: %s" % request.META)
    logging.info("request post vals: %s" % request.POST)
    logging.info("###########")
    resp.status_code = 403    
    resp.content="ForbiddenAccess"   
        
    user = users.get_current_user()
    logging.info("user%s" % user)
    #since it is authenticated, there should a user; still we will check
    if user:
        #time_details will be urlencoded (=all are string chars)
        #convert that back into list using eval
        client_time_details = eval(request.POST['time_details'])
        logging.info("Updating for user %s with vals:%s count is:%d" %(user, client_time_details, len(client_time_details)))        
        for time_snapshot in client_time_details:
            logging.info("snapshot is from:%s" % time_snapshot['source'])
            time = time_details()
            time.user = user            
            yr,mon,dt,hr,min,sec = strToDateTime(time_snapshot['fromtime'])            
            time.fromtime = datetime.datetime(yr, mon, dt, hr, min, sec)
            yr,mon,dt,hr,min,sec = strToDateTime(time_snapshot['totime'])
            time.totime = datetime.datetime(yr, mon, dt, hr, min, sec)               
            time.timespent = time_snapshot['timespent']
            time.task = time_snapshot['task']            
            time.taskinfo = time_snapshot['taskinfo']            
            time.ipaddress = time_snapshot['ipaddress']            
            time.osversion = time_snapshot['osversion']            
            time.source = time_snapshot['source']            
            time.uploadedtime = datetime.datetime.now()    
            time.put()                
    resp.status_code=200
    resp.content="Updated Successfully"
    return resp